import {
  ref,
  toRefs,
  toRef,
  computed,
  watch,
  onBeforeUnmount,
  onMounted
} from 'vue';

import { useEchart } from '@/hooks/use-echarts';

import emitter from '@/utils/bus.js';

import { getComponentShowListApi } from '@/views/design-center/api/screen';

export const useChartComponentData = (
  props,
  mockData,
  chartTypeConfig,
  y1ChartTypeConfig = {}
) => {
  const chartEl = ref(null);

  const dynamicData = ref(null); //动态数据初始值

  let timer = null;

  const { value } = toRefs(props);

  const { setups, styles } = toRefs(props.value);

  // console.log('获取组件的配置项--------', setups.value);
  // console.log('获取组件的配置项-----styles---', styles.value);
  // console.log('获取组件的---样式--------配置项--------', props.value);

  const { updateEchart, resizeHandler } = useEchart(chartEl, props);

  const preview = toRef(props, 'preview');

  // 是否关联了数据集
  const isConfigDataSets = computed(() => {
    return !!setups.value.associatedDatasets.id;
  });

  /**
   * @description: 监听组件传递过来的值后,更新echart图
   * @return {*}
   */
  watch(
    () => value,
    () => {
      updateData();
    },
    { deep: true }
  );

  /**
   * @description:echarts options配置项
   * @return {*}
   */
  const getOption = () => {
    let option = null;
    if (dynamicData.value) {
      if (chartTypeConfig?.type === 'pie') {
        //饼图类
        option = {
          series: [
            {
              type: 'pie',
              center: [
                `${styles.value.xPosition}%`,
                `${styles.value.yPosition}%`
              ],
              radius: [
                `${styles.value.startRadius}%`,
                `${styles.value.endRadius}%`
              ],
              label: {
                //饼图图形上的文本标签
                position: 'outside', //outside-饼图扇区外侧  inside-饼图扇区内部
                color: '#000',
                show: true
              },
              data: dynamicData.value.map((item) => {
                return {
                  name: item[setups.value.xAxis[0]?.value],
                  xKey: setups.value.xAxis[0]?.value,
                  value: item[setups.value.barChartValue[0]?.value]
                };
              }),
              emphasis: {
                // itemStyle: {
                //   shadowBlur: 10,
                //   shadowOffsetX: 0,
                //   // shadowColor: 'rgba(0, 0, 0, 0.5)'
                // }
              }
            }
          ]
        };
        if (preview.value) {
          //鼠标悬浮提示
          option.tooltip = {
            trigger: 'item'
          };
        }
        option.color = styles.value.chartColorArr || ''; //图形颜色数组
      } else if (chartTypeConfig?.type === 'widget-bar-columnar') {
        //条形柱状图
        option = {
          xAxis: {
            type: 'value'
          },
          yAxis: setups.value.barChartValue.map((el, index) => {
            return {
              type: 'category',
              data: dynamicData.value.map((item) => item[el.value])
            };
          }),
          series: setups.value.xAxis.map((el) => {
            return {
              type: 'bar',
              name: styles.value.axisTitleShowX
                ? setups.value.xAxis[0]?.label
                : '',

              data: dynamicData.value.map((item) => item[el.value])
            };
          })
        };
        option.color = styles.value.chartColorArr || ''; //图形颜色数组
      } else if (chartTypeConfig?.type === 'wave') {
        // console.log(
        //   '水球图数据',
        //   setups.value.barChartValue.map((el, index) => {
        //     return dynamicData.value.map((item) => item[el.value]);
        //   })
        // );
        let waveData = setups.value.barChartValue.map((el, index) => {
          return dynamicData.value.map((item) => {
            return {
              name: item[setups.value.xAxis[0]?.value],
              xKey: setups.value.xAxis[0]?.value,
              value: item[el.value] / 100
            };
          });
        });

        //水球图
        option = {
          series: [
            {
              type: 'liquidFill',
              data: waveData.flat(),
              color: styles.value.chartColorArr || ['#4366f3'], //设置颜色系列
              label: {
                fontSize: 18,
                fontWeight: 600,
                position: ['50%', '65%'] //文字所在位置
              },
              outline: {
                borderDistance: 0, //边框距离
                itemStyle: {
                  borderWidth: 1,
                  borderColor: 'blue',
                  shadowBlur: 10
                }
              }
            }
          ]
        };
      } else if (chartTypeConfig?.type === 'sunburst') {
        // 基础旭日图
        option = {};
      } else if (chartTypeConfig?.type === 'radar') {
        // 折线雷达图
        option = {
          radar: {
            shape: 'circle',
            // indicator: [{ name: '张三' }, { name: '李四' }, { name: '王五' }]
            indicator: setups.value.xAxis
              .map((el) => {
                return dynamicData.value.map((item) => {
                  {
                    return {
                      text: item[el.value]
                    };
                  }
                });
              })
              .flat()
          },
          series: [
            {
              type: 'radar',
              data: setups.value.barChartValue.map((el, index) => {
                return {
                  name: el.label, //图例名称
                  value: dynamicData.value.map((item) => item[el.value]),
                  areaStyle: {
                    color: styles.value.chartColorArr[index]
                  }
                };
              })
            }
          ]
        };
      } else if (chartTypeConfig?.type === 'gauge') {
        // 仪表盘
        option = {
          // tooltip: {
          //   // formatter: `${setups.value.xAxis[0].label}:${xData[0].data[0]}  `
          // },
          series: [
            {
              name: setups.value.xAxis[0].label,
              type: 'gauge',
              splitNumber: setups.value.splitNumber, //分几份
              progress: {
                show: true,
                width: 2
              },
              axisLine: {
                lineStyle: {
                  width: 1
                },
                color: [
                  [0.3, '#f4664a'],
                  [0.7, '#faad14'],
                  [1, '#30bf78']
                ]
              },

              detail: {
                valueAnimation: true, //动效
                textStyle: {
                  fontSize: 18
                }
              },

              data: setups.value.barChartValue.map((el, index) => {
                console.log('el', el);
                return {
                  name: el.label,
                  xKey: el.value,
                  value: dynamicData.value.map((item) => item[el.value])
                };
              })
            }
          ]
        };
        if (chartTypeConfig.childType === 'widget-meter-gauge') {
          option.axisTick = {
            distance: -25,
            length: 25,
            lineStyle: {
              color: '#fff',
              width: 3
            }
          };
        }
      } else {
        // console.log('mockData.yAxis-------', mockData.yAxis);
        //主轴的数据
        let ySeries = setups.value.barChartValue.map((el, index) => {
          return {
            name: el.label, //图例名称
            data: dynamicData.value.map((item) => {
              return {
                name: item[el.value],
                // xKey: el.value,
                value: item[el.value]
              };
            }),
            ...chartTypeConfig,
            itemStyle: {
              //这里设置柱形图圆角 [左上角，右上角，右下角，左下角]
              borderRadius: [
                styles.value[`${el.value}_barBorderRadius`] || 0,
                styles.value[`${el.value}_barBorderRadius`] || 0,
                0,
                0
              ]
            },
            barWidth: styles.value[`${el.value}_barW`]
          };
        });
        //次轴的数据
        let y1Series =
          setups.value?.y1Axis?.map((el, index) => {
            return {
              name: el.label, //图例名称
              data: dynamicData.value.map((item) => {
                return {
                  name: item[el.value],
                  // xKey: el.value,
                  value: item[el.value]
                };
              }),
              ...y1ChartTypeConfig,
              smooth: styles.value[`${el.value}_lineSmooth`]
            };
          }) || [];

        let dealYAxis = undefined;
        if (Array.isArray(mockData?.yAxis)) {
          dealYAxis = [
            {
              // 主纵坐标
              type: 'value',
              name: styles.value.axisTitleShowY
                ? setups.value.barChartValue[0].label
                : '', //X轴标题
              splitLine: { show: false } //隐藏背景网格线
            },
            {
              //次纵坐标
              type: 'value',
              name: styles.value.axisTitleShowY1
                ? setups.value.y1Axis[0].label
                : '', //X轴标题
              splitLine: { show: false } //隐藏背景网格线
            }
          ];
        } else {
          dealYAxis = {
            name: styles.value.axisTitleShowY
              ? setups.value.y1Axis[0].label
              : '', //X轴标题
            type: 'value',
            splitLine: { show: false } //隐藏背景网格线
          };
        }

        //折线和柱状图
        option = {
          xAxis: setups.value.xAxis.map((el) => {
            console.log(el, '看下请求字段----------');
            return {
              // type: 'category',
              name: styles.value.axisTitleShowX
                ? setups.value.xAxis[0].label
                : '', //X轴标题
              xKey: el.value,
              data: dynamicData.value.map((item) => item[el.value])
            };
          }),
          yAxis: dealYAxis,
          series: [...ySeries, ...y1Series]
        };
        //鼠标悬浮提示

        if (preview.value) {
          option.tooltip = {
            trigger: 'axis'
          };
        }
        //设置横坐标的样式
        if (option?.xAxis?.length) {
          option.xAxis = option?.xAxis?.map((item) => {
            return {
              ...item,
              axisLabel: {
                color: styles.value.xAxisLabelColor,
                fontSize: styles.value.xAxisLabelFontSize,
                rotate: styles.value.xAxisLabelRotate
                // clickable: true
              }
            };
          });
        }

        //设置主坐标的样式
        //注意y轴可以是对象,也可以是数组
        if (option?.yAxis) {
          // console.log(option?.yAxis);
          if (Array.isArray(option?.yAxis)) {
            option.yAxis[0] = {
              ...option.yAxis[0],
              axisLabel: {
                show: styles.value.showYAxis,
                color: styles.value.yAxisLabelColor,
                fontSize: styles.value.yAxisLabelFontSize,
                rotate: styles.value.yAxisLabelRotate
              }
            };
            option.yAxis[1] = {
              ...option.yAxis[1],
              axisLabel: {
                show: styles.value.showYAxis1,
                color: styles.value.yAxis1LabelColor,
                fontSize: styles.value.yAxis1LabelFontSize,
                rotate: styles.value.yAxis1LabelRotate
              }
            };
          } else {
            option.yAxis = {
              ...option?.yAxis,
              axisLabel: {
                show: styles.value.showYAxis,
                color: styles.value.yAxisLabelColor,
                fontSize: styles.value.yAxisLabelFontSize,
                rotate: styles.value.yAxisLabelRotate
              }
            };
          }
        }

        option.color = styles.value.chartColorArr || ''; //图形颜色数组
      }
    } else {
      option = mockData;
    }

    console.log('最新的options------------', option);

    /** ----------公共配置项--------**/

    // 设置背景颜色
    option.backgroundColor = styles.value.componentBg;

    let includeFlag = ['top', 'bottom'].includes(styles.value.legendPosition);

    // 设置是否显示图例
    option.legend = {
      show: styles.value.legendShow,
      orient: includeFlag ? 'horizontal' : 'vertical',
      left: includeFlag ? 'center' : styles.value.legendPosition,
      top: includeFlag ? styles.value.legendPosition : 'center',
      textStyle: {
        //图例字体大小
        fontSize: styles.value.legendFontSize,
        color: styles.value.legendColor
      }
      // top: '10%' //图例距离顶部距离
    };

    //标题
    option.title = {
      text: setups.value.componentName,
      left: styles.value.titlePosition,
      textStyle: {
        // 标题美化
        color: styles.value.echartsTitleColor, // 标题颜色--红
        fontSize: styles.value.echartsTextFontsize
      }
    };

    // console.log('更新的option----------', option);
    return option;
  };

  /**
   * @description:更新echarts图表展示
   * @return {*}
   */
  const updateData = () => {
    updateEchart(getOption());
  };

  /**
   * @description:获取试图的动态数据
   * @param {对象} value查询参数
   * @return {*}
   */
  const getDynamicData = async (value = {}) => {
    let res = await getComponentShowListApi({
      dataSetId: setups.value?.associatedDatasets?.id,
      ...value
    });
    dynamicData.value = res.data;
    updateData();
  };
  /**
   * @description:获取服务端数据数据
   * @return {*}
   */
  const refreshData = () => {
    if (isConfigDataSets.value) {
      //初始化的时候先请求一次,然后再按照定时请求请求
      getDynamicData();
      if (preview.value) {
        timer = setInterval(() => {
          getDynamicData();
        }, 50000);
      }
    } else {
      updateEchart(getOption());
    }
  };
  /**
   * @description:绑定其它组件的联动
   * @return {*}
   */
  emitter.on(props.value?.id, (data) => {
    // console.log('触发了吗', data);
    getDynamicData(data);
  });

  onBeforeUnmount(() => {
    emitter.off(props.value?.id); //关闭
    clearInterval(timer);
    timer = null;
  });

  onMounted(async () => {
    refreshData();
  });
  return {
    chartEl,
    resizeHandler,
    styles,
    preview
  };
};
